package com.cunyu.listener;

import java.io.IOException;
import java.sql.DriverManager;
import java.util.Properties;

import javax.servlet.ServletContextEvent;

import com.cunyu.util.PropertiesUtil;
import com.cunyu.util.Resource;
import org.springframework.web.context.ContextLoaderListener;

import ch.qos.logback.ext.spring.web.WebLogbackConfigurer;

public class Listener extends ContextLoaderListener{

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		super.contextInitialized(arg0);
		WebLogbackConfigurer.initLogging(arg0.getServletContext());
		
		//Log4jWebConfigurer.initLogging(arg0.getServletContext());
		String webRoot = arg0.getServletContext().getRealPath("");
		loadAppprops(webRoot);
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		super.contextDestroyed(arg0);
		 try{
             while(DriverManager.getDrivers().hasMoreElements()){
                 DriverManager.deregisterDriver(DriverManager.getDrivers().nextElement());
            }
         }catch(Exception e){
             e.printStackTrace();
         }
	}

	private void loadAppprops(String webRoot) {
		Resource resource = new Resource("/WEB-INF/cfg/app.properties");
		resource.setWebRoot(webRoot);
		Properties props = null;
		try {
			props = PropertiesUtil.loadProperties(resource);
			props.put("webroot", webRoot);
		} catch (IOException e) {}
		Constants.apps.putAll(PropertiesUtil.toMap(props));	
		System.out.println("APPconfig===" +Constants.apps);
	}
	
}
